package org.kernely.security.ui.user.mgmt;

import java.util.HashSet;
import java.util.Set;

import org.kernely.security.dao.RoleDAO;
import org.kernely.security.persistence.Role;
import org.kernely.security.persistence.UserDetails;
import org.kernely.ui.mvp.KernelyPresenter;

import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.CheckBox;

public class EditUserRolePresenter extends KernelyPresenter<EditUserRoleView>{

	/**
	 * UserDetails to edit in edition mode
	 */
	private UserDetails ud;
	/**
	 * Set containing all user's roles
	 */
	private Set<Role> userRoles = new HashSet<Role>();
	private boolean editMode = false;
	
	/**
	 * Default constructor in creation mode
	 */
	public EditUserRolePresenter(){}
	
	/**
	 * Constructor in edition mode
	 * @param ud : the UserDetails to edit
	 */
	public EditUserRolePresenter(UserDetails ud){
		this.ud = ud;
		this.editMode = true;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.kernely.ui.mvp.KernelyPresenter#bind()
	 */
	@Override
	public final void bind() {
		if(editMode){
			userRoles.addAll(ud.getUser().getRoles());
		}
		RoleDAO rdao = new RoleDAO();
		
		for(Role r : rdao.getAllRoles()){
			final RoleCheckBox rcb;
			if(userRoles.contains(r)){
				rcb = new RoleCheckBox(r.getName(), true, r);
			}
			else{
				rcb = new RoleCheckBox(r.getName(), false, r);
			}
			rcb.addListener(new ValueChangeListener(){
				private static final long serialVersionUID = -2761797639733607828L;

				@Override
				public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
					if((Boolean)rcb.getValue()){
						userRoles.add(rcb.getAssociatedRole());
					}
					else{
						userRoles.remove(rcb.getAssociatedRole());
					}
				}
				
			});
			view.getRoleLayout().addComponent(rcb);
		}
		
		
	}
	
	/**
	 * Gets user's roles list
	 * @return the user's roles list
	 */
	public final Set<Role> getUserRoles(){
		return this.userRoles;
	}
	
	/**
	 * Default constructor
	 * @param caption : CheckBox's caption
	 * @param defaultValue : CheckBox's default value : true or false
	 * @param role : role associated to this checkBox
	 */
	private final class RoleCheckBox extends CheckBox{
		private static final long serialVersionUID = -5754594621339389249L;
		
		/**
		 * Associated role to this checkBox
		 */
		private Role associatedRole;
		
		/**
		 * Constructor
		 * @param caption : caption of the checkbox
		 * @param defaultValue : default value of the checkbox : true or false
		 * @param role : role associated to this checkbox
		 */
		public RoleCheckBox(String caption,boolean defaultValue, Role role){
			this.setCaption(caption);
			this.setValue(defaultValue);
			this.setImmediate(true);
			this.associatedRole = role;
		}
		
		/**
		 * Gets the role associated to this checkbox
		 * @return the role associated to this checkbox
		 */
		public final Role getAssociatedRole(){
			return this.associatedRole;
		}
	}

}
